<?php

namespace app\index\controller;

use app\common\JwtHelper;
use app\middleware\SecurityMiddleware;
use think\Controller;
use think\Db;
use think\Request;
use think\Validate;

class Api extends Controller
{
    public function __construct()
    {
        parent::__construct();

        // 调用中间件
        $middleware = new SecurityMiddleware();
        $request = Request::instance();
        $middleware->handle($request, function ($req) {
            // 仅执行验证，不做中间件链路回调
            return response(); // 返回空响应对象用于中间件添加响应头
        });
    }

    public function testApi()
    {
        apiReturn(1,'成功');
    }


    public static function checkUserStatus($user_id)
    {
        $info = Db::name('user')->where('id', $user_id)->find();
        if (empty($info)) apiReturn(401, '账号不存在');
        if ($info['status'] == 2) apiReturn(401, '账号已被禁用');
    }

    public static function authorizationGetUserId()
    {
        $request = request(); // 获取当前请求

        $authHeader = $request->header('authorization', '');

        if ($authHeader && stripos($authHeader, 'Bearer ') === 0) {
            $token = substr($authHeader, 7);
            $payload = JwtHelper::verifyToken($token);

            if ($payload && !empty($payload['user_id'])) {
                // 可选：自动续期（设置响应头，供中间件读取）
                if (JwtHelper::shouldRefreshToken($payload)) {
                    $newToken = JwtHelper::createToken(['user_id' => $payload['user_id']]);
                    header('X-Refreshed-Token: ' . $newToken);
                }
            }
        }
        $user_id = $payload['user_id'] ? : '';
        if ($user_id) {
            self::checkUserStatus($user_id);
        }
        return $user_id;
    }

    /**
     * 发送验证码
     * */
    public function sendSms()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $type = $input['type'] ? : 'register';

        if (empty($mobile)) apiReturn(2, '请输入手机号');

        $time = time();

        //获取手机号
        $pattern = "/^1[0123456789]\d{9}$/";
        if (preg_match($pattern, $mobile)) {
            $result = Db::name('sms_code')->where(['mobile' => $mobile, 'type' => $type])->order('create_time desc')->find();
            $result = $time - $result['create_time'];
            if ($result < 60 && $result > 0) apiReturn(2, '当前手机号操作频繁,请60秒后发送');

            $code = rand(100000, 999999);
            $statusStr = [
                "0" => 1,
                "-1" => "参数不全",
                "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
                "30" => "密码错误",
                "40" => "账号不存在",
                "41" => "余额不足",
                "42" => "帐户已过期",
                "43" => "IP地址限制",
                "50" => "内容含有敏感词"
            ];
            $smsapi = "http://api.smsbao.com/";
            $user = C('SMS_ACC');                                                         // 短信平台帐号
            $pass = md5(C('SMS_PWD'));                                                    // 短信平台密码
            $content = "【湖南畅途汽车科技】您的验证码是{$code}。如非本人操作，请忽略本短信"; // 要发送的短信内容
            $url = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $mobile . "&c=" . urlencode($content);
            $result = file_get_contents($url);
            if ($result == 0) {
                Db::name('sms_code')->where("`mobile` = '{$mobile}' AND ( `is_failure` = 0 OR `failure_time` < {$time} )")->setField('is_failure', 1);

                $info['code'] = $code;
                $info['mobile'] = $mobile;
                $info['create_time'] = $time;
                $info['failure_time'] = $time + 600;//失效时间：10分钟
                $info['type'] = $type;
                Db::name('sms_code')->insert($info);

                apiReturn(1, '短信发送成功', $code);
            } else {
                apiReturn(2, $statusStr[$result]);
            }
        } else {
            apiReturn(2, '手机号码格式错误');
        }
    }

    /**
     * 注册
     * */
    public function register()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $password = $input['password'];
        $sms_code = $input['sms_code'];
        $code = $input['code'] ? : '';

        if (empty($mobile)) apiReturn(2, '请输入手机号码');
        if (empty($password)) apiReturn(2, '请输入密码');
        if (empty($sms_code)) apiReturn(2, '请输入验证码');

        $user_info = Db::name('user')->where(['mobile' => $mobile, 'is_admin' => 0])->find();
        if ($user_info) apiReturn(2, '该手机号已被注册');

        $validate = new Validate([
                                     'password' => 'require|regex:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/'
                                 ]);
        if (!$validate->check(['password' => $password])) apiReturn(2, '密码由6位以上大小写字母和数字组合');

        $sms_code_info = Db::name('sms_code')->where(['mobile' => $mobile, 'code' => $sms_code, 'type' => 'register'])->find();
        if (!$sms_code_info) apiReturn(2, '验证码错误');
        if ($sms_code_info['failure_time'] < time() || $sms_code_info['is_failure'] == 1) apiReturn(2, '验证码已过期');

        if ($code) {
            $spread_user_info = Db::name('user')->where(['code' => $code])->find();
            if (!$spread_user_info) apiReturn(2, '推广码错误');
            if ($spread_user_info['status'] == 2) adminReturn(2, '该推广码已被禁用');
        }

        Db::startTrans();
        try {
            $data = [
                'account' => $mobile,
                'mobile' => $mobile,
                'password' => thinkEncrypt($password),
                'user_type' => 3,
                'up_user_id' => $spread_user_info['id'] ? : 0
            ];
            $res = Db::name('user')->insert($data);
            if (!$res) {
                Db::rollback();
                apiReturn(2, '注册失败');
            }

            Db::name('sms_code')->where(['id' => $sms_code_info['id']])->setField('is_failure', 1);

            Db::commit();
            apiReturn(1, '注册成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '注册失败');
        }
    }

    /**
     * 忘记密码
     * */
    public function forgetPassword()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $password = $input['password'];
        $sms_code = $input['sms_code'];

        if (empty($mobile)) apiReturn(2, '请输入手机号码');
        if (empty($password)) apiReturn(2, '请输入密码');
        if (empty($sms_code)) apiReturn(2, '请输入验证码');

        $user_info = Db::name('user')->where(['mobile' => $mobile, 'is_admin' => 0])->find();
        if (empty($user_info)) apiReturn(2, '该手机号未注册');

        $validate = new Validate([
                                     'password' => 'require|regex:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/'
                                 ]);
        if (!$validate->check(['password' => $password])) apiReturn(2, '密码由6位以上大小写字母和数字组合');

        $sms_code_info = Db::name('sms_code')->where(['mobile' => $mobile, 'code' => $sms_code, 'type' => 'forget'])->find();
        if (!$sms_code_info) apiReturn(2, '验证码错误');
        if ($sms_code_info['failure_time'] < time() || $sms_code_info['is_failure'] == 1) apiReturn(2, '验证码已过期');

        Db::startTrans();
        try {
            $data = [
                'password' => thinkEncrypt($password),
                'update_time' => time()
            ];
            $res = Db::name('user')->where(['id' => $user_info['id']])->update($data);
            if (!$res) {
                Db::rollback();
                apiReturn(2, '修改密码失败');
            }

            Db::name('sms_code')->where(['id' => $sms_code_info['id']])->setField('is_failure', 1);

            Db::commit();
            apiReturn(1, '修改密码成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '修改密码失败');
        }
    }

    /**
     * 登录
     * */
    public function login()
    {
        $input = Request()->param();

        $mobile = $input['mobile'];
        $password = $input['password'];

        if (empty($mobile)) apiReturn(2, '请输入手机号码');
        if (empty($password)) apiReturn(2, '请输入密码');

        $user_info = Db::name('user')->where(['mobile' => $mobile, 'is_admin' => 0])->find();
        if (empty($user_info)) apiReturn(2, '该手机号未注册');
        if ($user_info['status'] == 2) apiReturn(2, '该账号已被禁用');

        if (thinkEncrypt($password) !== $user_info['password']) apiReturn(2, '密码错误');

        $token = JwtHelper::createToken(['user_id' => $user_info['id']]);

        apiReturn(1, '登录成功', $token);
    }

    /**
     * 获取客服电话
     * */
    public function getContactTel()
    {
        $contact_tel = C('CONTACT_TEL');
        apiReturn(1, '获取数据成功', $contact_tel ? : '');
    }

    /**
     * banner列表
     * */
    public function bannerList()
    {
        $list = Db::name('banner')->order('id desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getHost() . $v['img'];
            }
        }

        apiReturn(1, '获取数据成功', $list ? : []);
    }

    /**
     * 文章详情
     * */
    public function articleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '参数错误');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time'], 'Y-m-d H:i');

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在');
        }
    }

    /**
     * 消息列表
     * */
    public function msgList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $user_id = self::authorizationGetUserId() ? : 0;

        $in = [0];
        if ($user_id) $in[] = $user_id;

        $list = Db::name('msg')->whereIn('user_id', $in)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = date('Y-m-d', $v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 我的
     * */
    public function userCenter()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户不存在');

        $user_info['avatar'] = $user_info['avatar'] ? getHost() . $user_info['avatar'] : '';

        $not_pay_count = Db::name('order')->where(['user_id' => $user_id, 'pay_time' => 0])->count();
        $user_info['not_pay_count'] = $not_pay_count;

        $status = Db::name('user_ident')->where('user_id', $user_id)->value('status');
        $user_info['ident_status'] = $status == 2 ? 1 : 0;

        $order_info = Db::name('order')->where(['user_id' => $user_id, 'status' => 2])->find();
        if ($order_info) {
            $user_info['number'] = $order_info['number'];
            $user_info['model'] = $order_info['model'];
            $end_time = strtotime($order_info['end_time']);
            if ($end_time > time()) {
                $user_info['remaining_time'] = $end_time;
            } else {
                $user_info['remaining_time'] = 0;
            }
        }

        $pay_type = C('PAY_TYPE');
        $pay_img = C('PAY_IMG');
        $pay_vip_img = C('PAY_VIP_IMG');

        $user_info['pay_type'] = $pay_type;
        $user_info['pay_img'] = $pay_img ? getHost() . $pay_img : '';
        $user_info['pay_vip_img'] = $pay_vip_img ? getHost() . $pay_vip_img : '';

        apiReturn(1, '获取数据成功', $user_info);
    }

    /**
     * 保存资料
     * */
    public function saveUserInfo()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $avatar = $input['avatar'];
        $username = $input['username'];
        $mobile = $input['mobile'];

        if (empty($avatar)) apiReturn(2, '请上传头像');
        if (empty($username)) apiReturn(2, '请输入姓名');
        if (empty($mobile)) apiReturn(2, '请输入手机号码');

        $data = [
            'avatar' => str_replace(getHost(), '', $avatar),
            'username' => $username,
            'mobile' => $mobile,
            'update_time' => time()
        ];
        $res = Db::name('user')->where(['id' => $user_id])->update($data);

        if ($res) {
            apiReturn(1, '保存成功');
        } else {
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 保存地址
     * */
    public function saveAddress()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $region_value = $input['region_value'];
        $region_index = $input['region_index'];
        $address_detail = $input['address_detail'];

        if (empty($region_value)) apiReturn(2, '请选择省市区');
        if (empty($address_detail)) apiReturn(2, '请输入详细地址');

        $data = [
            'region_value' => $region_value,
            'region_index' => $region_index,
            'address_detail' => $address_detail,
            'update_time' => time()
        ];

        $res = Db::name('user')->where(['id' => $user_id])->update($data);
        if ($res) {
            apiReturn(1, '保存成功');
        } else {
            apiReturn(2, '保存失败');
        }
    }

    /**
     * 获取权益福利文章数据
     * */
    public function getVipArticle()
    {
        $info = Db::name('vip_article')->where('id', 1)->find();
        $info['content'] = doEditorContent($info['content']);

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 我的车友
     * */
    public function mySpread()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('user')->field('id,username,avatar,create_time')->where(['up_user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = $v['avatar'] ? getHost() . $v['avatar'] : '';

                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');

                $status = Db::name('user_ident')->where(['user_id' => $v['id']])->value('status');
                $v['is_ident'] = $status == 2 ? 1 : 0;
            }
        }

        $count = Db::name('user')->where(['up_user_id' => $user_id])->count();

        $data = [
            'count' => $count,
            'list' => $list
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 申请合作
     * */
    public function apply()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $id = $input['id'] ? : 0;
        $username = $input['username'];
        $mobile = $input['mobile'];
        $desc = $input['desc'] ? : '';

        if (empty($username)) apiReturn(2, '请输入姓名');
        if (empty($mobile)) apiReturn(2, '请输入手机号');

        $data = [
            'user_id' => $user_id,
            'username' => $username,
            'mobile' => $mobile,
            'desc' => $desc,
        ];
        if ($id) {
            $data['update_time'] = time();
            $res = Db::name('user_apply')->where(['id' => $id])->update($data);
        } else {
            $data['create_time'] = time();
            $res = Db::name('user_apply')->insert($data);
        }

        if ($res) {
            apiReturn(1, '申请成功');
        } else {
            apiReturn(2, '申请失败');
        }
    }

    /**
     * 查看申请合作信息
     * */
    public function applyInfo()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $info = Db::name('user_apply')->field('id,username,mobile,desc,status')->where(['user_id' => $user_id])->find();

        if ($info) {
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 我的车队
     * */
    public function teamList()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $list = Db::name('user_team_car t')->join('le_car c', 't.car_id = c.id')
            ->field('c.id,c.model,c.number,t.all_profit,t.status')
            ->where(['t.user_id' => $user_id])
            ->order('t.id desc')
            ->select();

        if ($list) {
            foreach ($list as &$v) {
                $v['all_profit'] = number_format($v['all_profit']);
                $v['status'] = $v['status'] == 1 ? '空闲中' : '租用中';
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 我的收益
     * */
    public function profitList()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $type = $input['type'] ? : '';
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['user_id'] = $user_id;

        if ($type) $where['type'] = $type;

        $list = Db::name('profit_log')->field('id,profit,remark,create_time')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $v['profit'] = $v['profit'] > 0 ? '+' . $v['profit'] : $v['profit'];
            }
        }

        $all_profit = Db::name('profit_log')->where(['user_id' => $user_id, 'type' => $type])->sum('profit');

        $data = [
            'all_profit' => $all_profit,
            'list' => $list
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 提交认证
     * */
    public function saveUserIdent()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $id = $input['id'] ? : 0;
        $username = $input['username'];
        $mobile = $input['mobile'];
        $id_card = $input['id_card'];
        $driver_license = $input['driver_license'];
        $card_z = $input['card_z'];
        $card_f = $input['card_f'];

        if (empty($username)) apiReturn(2, '请输入姓名');
        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (empty($id_card)) apiReturn(2, '请输入身份证号');
        if (empty($driver_license)) apiReturn(2, '请输入驾驶证号码');
        if (empty($card_z)) apiReturn(2, '请上传身份证正面');
        if (empty($card_f)) apiReturn(2, '请上传身份证反面');

        $data = [
            'user_id' => $user_id,
            'username' => $username,
            'mobile' => $mobile,
            'id_card' => $id_card,
            'driver_license' => $driver_license,
            'card_z' => $card_z ? str_replace(getHost(), '', $card_z) : '',
            'card_f' => $card_f ? str_replace(getHost(), '', $card_f) : '',
            'status' => 1
        ];

        if ($id) {
            $data['update_time'] = time();

            $res = Db::name('user_ident')->where(['id' => $id])->update($data);
        } else {
            $data['create_time'] = time();
            $res = Db::name('user_ident')->insert($data);
        }

        if ($res) {
            apiReturn(1, '提交成功');
        } else {
            apiReturn(2, '提交失败');
        }
    }

    /**
     * 认证信息
     * */
    public function userIdentInfo()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $info = Db::name('user_ident')->where(['user_id' => $user_id])->find();
        if ($info) {
            $info['card_z'] = $info['card_z'] ? getHost() . $info['card_z'] : '';
            $info['card_f'] = $info['card_f'] ? getHost() . $info['card_f'] : '';
        }

        apiReturn(1, '获取数据成功', $info ? : []);
    }

    /**
     * 用户违章记录列表
     * */
    public function violationList()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('violation_log')->where(['user_id' => $user_id])->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 租车服务数据
     * */
    public function rentService()
    {
        $tip_one = C('TIP_ONE');
        $tip_two = C('TIP_TWO');
        $tip_three = C('TIP_THREE');

        $contact_tel = C('CONTACT_TEL');

        $know = Db::name('know_article')->where('id', 1)->value('content');
        if ($know) $know = doEditorContent($know);

        $data = [
            'tip_one' => $tip_one,
            'tip_two' => $tip_two,
            'tip_three' => $tip_three,
            'contact_tel' => $contact_tel,
            'know' => $know
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 提交订单预约
     * */
    public function slotOrder()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $count = Db::name('slot_order')->where(['user_id' => $user_id, 'order_id' => 0])->count();
        if ($count) apiReturn(2, '您已预约，请勿重复预约');

        $count = Db::name('slot_order')->where(['user_id' => $user_id, 'is_end' => 0])->count();
        if ($count) apiReturn(2, '您有未结束的订单，请勿重复预约');

        Db::startTrans();
        try {
            $slot_order_data = [
                'user_id' => $user_id,
                'create_time' => time()
            ];

            $res = Db::name('slot_order')->insert($slot_order_data);

            if ($res) {
                Db::commit();
                apiReturn(1, '提交预约成功');
            } else {
                Db::rollback();
                apiReturn(2, '提交预约失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '提交预约失败');
        }
    }

    /**
     * 上传付款凭证
     * */
    public function uploadPayedImg()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $id = $input['id'];// 订单id
        $payed_img = $input['payed_img'];

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if (empty($payed_img)) apiReturn(2, '请上传付款凭证');

        $info = Db::name('order')->where('id', $id)->find();

        if (empty($info)) apiReturn(2, '订单不存在');
        if ($info['user_id'] != $user_id) apiReturn(2, '订单异常');

        $data = [
            'order_id' => $id,
            'payed_img' => str_replace(getHost(), '', $payed_img),
            'payed_status' => 1,
            'update_time' => time()
        ];

        if ($info['type'] == 1) {
            // 新开
            $info = Db::name('order_payed')->where(['order_id' => $id])->find();

            $data['payed_type'] = 1;

            if (empty($info)) {
                $res = Db::name('order_payed')->insert($data);
            } else {
                $payed_id = Db::name('order_payed')->where(['order_id' => $id, 'payed_status' => ['IN', [1, -1]]])->max('id');
                if ($payed_id) {
                    $res = Db::name('order_payed')->where(['id' => $payed_id])->update($data);
                } else {
                    $res = Db::name('order_payed')->insert($data);
                }
            }
        } else {
            $data['payed_type'] = 2;
            // 续费
            $new_id = Db::name('order_payed')->where(['order_id' => $id, 'payed_type' => 2])->max('id');
            if ($new_id) {
                $payed_info = Db::name('order_payed')->where(['id' => $new_id])->find();
                if ($payed_info['payed_status'] == 2) {
                    $res = Db::name('order_payed')->insert($data);
                } elseif ($payed_info['payed_status'] == -1) {
                    $res = Db::name('order_payed')->where(['id' => $new_id])->update($data);
                } else {
                    apiReturn(2, '凭证数据异常');
                }
            } else {
                $res = Db::name('order_payed')->insert($data);
            }
        }

        if ($res) {
            apiReturn(1, '上传成功');
        } else {
            apiReturn(2, '上传失败');
        }
    }

    /**
     * 订单列表
     * */
    public function orderList()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['user_id'] = $user_id;
        if ($status) $where['status'] = $status;

        $list = Db::name('order')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $max_id = Db::name('order_payed')->where(['order_id' => $v['id']])->max('id');
                $payed_info = Db::name('order_payed')->where(['id' => $max_id])->find();

                $v['payed_img'] = $payed_info['payed_img'] ? getHost() . $payed_info['payed_img'] : '';
                $v['payed_status'] = $payed_info['payed_status'] ? : 0;
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 上传VIP付款凭证
     * */
    public function uploadVipPayedImg()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $input = Request()->param();

        $payed_img = $input['payed_img'];

        if (empty($payed_img)) apiReturn(2, '请上传付款凭证');

        $data = [
            'user_id' => $user_id,
            'price' => C('VIP_PRICE'),
            'payed_img' => str_replace(getHost(), '', $payed_img),
            'payed_status' => 1,
        ];
        $time = time();

        $count = Db::name('vip_order')->where('user_id', $user_id)->count();
        if ($count) {
            $data['update_time'] = $time;
            $res = Db::name('vip_order')->where('user_id', $user_id)->update($data);
        } else {
            $data['order_sn'] = 'VIP' . date('Ymd') . rand(1000, 9999) . $user_id;
            $data['create_time'] = $time;
            $res = Db::name('vip_order')->insert($data);
        }

        if ($res) {
            apiReturn(1, '上传成功');
        } else {
            apiReturn(2, '上传失败');
        }
    }

    /**
     * 获取用户VIP相关信息
     * */
    public function getUserVipInfo()
    {
        $user_id = self::authorizationGetUserId();
        if (empty($user_id)) apiReturn(2, '请先登录');

        $info = Db::name('vip_order')->field('payed_img,payed_status')->where('user_id', $user_id)->find();
        if ($info) {
            $info['is_vip'] = $info['payed_status'] == 2 ? 1 : 0;

            apiReturn(1, '获取数据成功', $info);
        } else {
            $data = [
                'payed_img' => '',
                'payed_status' => 0,
                'is_vip' => 0,
            ];
            apiReturn(1, '获取数据成功', $data);
        }
    }
}
